package com.xinting.piano.app;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;

import com.xinting.piano.R;
import com.xinting.piano.data.PApp;
import com.xinting.piano.data.PError;
import com.xinting.piano.data.PMelody;
import com.xinting.piano.data.PUser;
import com.xinting.piano.lib.util.PUtil;
import com.xinting.piano.service.IHandleJson;
import com.xinting.piano.service.PAccount;
import com.xinting.piano.service.PAlbum;
import com.xinting.piano.service.PBroadcast;
import com.xinting.piano.view.ICustomControlView;
import com.xinting.piano.view.PAddControlView;
import com.xinting.piano.view.PControlView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PMainActivity extends PBaseActivity {

    private List<PMelody> melodies;
    private ListView melodiesView;

    private PControlView addMelody;
    private ICustomControlView addCustomControlView;

    private MelodyHandler handler;
    private SwipeRefreshLayout refreshLayout;
    private PMelodyAdapter adapter;

    //service
    private PAlbum album;
    private HandleMelodyResult handleMelodyResult;

    //最新的一条乐曲ID
    private Date newest;
    //最旧的一条乐曲ID
    private Date oldest;

    public static final String LOG_TAG = PApp.LOG_TAG+"_main";
    public static final String KEY_MELODIES = "melodies";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //login
        album = new PAlbum(null);

        handler = new MelodyHandler();
        melodies = new ArrayList<>();
        newest = new Date(0); // 设置一个很旧的时间
        oldest = new Date();

        melodiesView = $(R.id.list_melody);
        refreshLayout = $(R.id.list_refresh);
        addMelody = $(R.id.main_add_melody);

        adapter = new PMelodyAdapter(this, melodies);
        adapter.setTagAdapter(new PTagAdapter(this));
        adapter.setUserAdapter(new PUserAdapter(this));
        melodiesView.setAdapter(adapter);

        melodiesView.setOnItemClickListener(new OnMelodyItemClickListener());

        // 加载更多，和加载最新
        RefreshListener refreshListener = new RefreshListener();
        melodiesView.setOnScrollListener(refreshListener);
        refreshLayout.setOnRefreshListener(refreshListener);

//        添加乐曲, UI不和谐（已经隐藏）
        addCustomControlView = new PAddControlView();
        addMelody.addCustomControlView(addCustomControlView);
        addMelody.setCustomType(PApp.CONTROL_VIEW_ADD);
        addMelody.setOnClickListener(new OnAddMelodyListener());

        /**
         * 更新乐曲列表
         */
//        album.loadMelodies(melodies);
//        adapter.notifyDataSetChanged();

        handleMelodyResult = new HandleMelodyResult();
        if (PAccount.getInstance().getStatus() == PAccount.Status.LOGIN) {
            Log.v(LOG_TAG, "update imm");
            album.updateMelodies(null, newest, handleMelodyResult);
        } else {
            PBroadcast.getInstance().register(PApp.BC_ACCOUNT_STATUS_CHANGE, new PBroadcast.IListener() {
                @Override
                public void listen(Object data) {
                    if (data == PAccount.Status.LOGIN) {
                        Log.v(LOG_TAG, "update melodies in broadcast");
                        album.updateMelodies(null, newest, handleMelodyResult);
                    }
                }
            });
        }
    }

    /**
     * 添加乐曲的响应
     */
    private class OnAddMelodyListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            PAccount.Status status = PAccount.getInstance().getStatus();

            if (status == PAccount.Status.LOGIN) {
                intent.setClass(PMainActivity.this, PRecordActivity.class);
            } else {
                intent.setClass(PMainActivity.this, PApplyLoginActivity.class);
                intent.putExtra(PApp.KEY_NEXT, PRecordActivity.class.getName());
            }
            startActivity(intent);
        }
    }

    /**
     * pull refresh listener
     */
    private class RefreshListener implements SwipeRefreshLayout.OnRefreshListener, AbsListView.OnScrollListener {

        @Override
        public void onRefresh() {
            //增量更新
            album.updateMelodies(null, newest, handleMelodyResult);

            //三秒后消失
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    refreshLayout.setRefreshing(false);
                }
            }, 3000);
        }

        @Override
        public void onScrollStateChanged(AbsListView absListView, int i) {

        }

        @Override
        public void onScroll(AbsListView absListView, int i, int i1, int i2) {
            /**
             * 满足条件
             * 1、有可见元素
             * 2、上一次More操作已经完成，album服务处于待命状态
             * 3、有更多的历史
             * 4、滑动到了最底部
             */
            if (i2 > 1 && album.getStatus() == PAlbum.Status.NORMAL && album.isHasMore()
                    && absListView.getCount() - 1 == absListView.getLastVisiblePosition()) {
                Log.e(LOG_TAG, "list count: " + absListView.getCount() + "; last pos: " + absListView.getLastVisiblePosition());
                album.moreMelodies(null, oldest, handleMelodyResult);
            }
        }
    }

    /**
     * 主线程中的处理，更新UI等
     */
    private class MelodyHandler extends Handler {

        public final int WHAT_UPDATE_MELODY = 1;
        public final int WHAT_MORE_MELODY = 2;

        @Override
        public void handleMessage(Message msg) {

            if (msg.obj instanceof JSONObject) {
                JSONObject json = (JSONObject) msg.obj;
                try {
                    PError error = new PError();
                    error.fromJson(json);
                    if (error.getCode() != PError.ERR_SUCCESS) {
                        PUtil.toast(PApp.getAppContext(), error.getMsg());
                        return;
                    }

                    JSONArray melodiesJson = json.getJSONArray(KEY_MELODIES);
                    for (int i = 0; i < melodiesJson.length(); i++) {
                        PMelody melody = new PMelody();
                        melody.fromJson(melodiesJson.getJSONObject(i));

                        if (msg.what == WHAT_MORE_MELODY) {
                            melodies.add(melody);
                        } else {
                            melodies.add(i, melody);
                        }
                    }
                    if (!melodies.isEmpty()) {
                        newest = melodies.get(0).getDate();
                        oldest = melodies.get(melodies.size()-1).getDate();
                    }
                    //存储到数据库(暂时不用)
//                    album.saveMelodies(melodies);

                    adapter.notifyDataSetChanged();
                    refreshLayout.setRefreshing(false);
                } catch (JSONException e) {
                    Log.w(LOG_TAG, e.getMessage());
                }
            }
        }
    }

    /**
     * 处理返回的数据
     */
    private class HandleMelodyResult implements IHandleJson {

        @Override
        public void handleJson(JSONObject json) {
            Message msg = Message.obtain();
            msg.what = handler.WHAT_UPDATE_MELODY;
            if (album.getStatus() == PAlbum.Status.MORE) {
                msg.what = handler.WHAT_MORE_MELODY;
            }
            msg.obj = json;
            handler.sendMessage(msg);
        }
    }

    /**
     * 乐曲点击事件
     */
    private class OnMelodyItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent intent = new Intent();
            Object object = adapterView.getItemAtPosition(i);
            if (object instanceof PMelody) {
                intent.putExtra(PMelody.KEY, (Serializable) object);
            }
            intent.setClass(PMainActivity.this, PAlbumActivity.class);
            startActivity(intent);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        addMelody.addCustomControlView(addCustomControlView);
        addMelody.setCustomType(PApp.CONTROL_VIEW_ADD);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        Intent intent = new Intent();
        PAccount.Status status = PAccount.getInstance().getStatus();
        if (status != PAccount.Status.LOGIN) {
            intent.setClass(this, PApplyLoginActivity.class);
        }

        switch (id) {
            case R.id.menu_add:
                if (status == PAccount.Status.LOGIN) {
                    intent.setClass(this, PRecordActivity.class);
                } else {
                    intent.putExtra(PApp.KEY_NEXT, PRecordActivity.class.getName());
                }
                break;
            case R.id.menu_info:
                if (status == PAccount.Status.LOGIN) {
                    intent.setClass(this, PUserActivity.class);
                    intent.putExtra(PUser.KEY, PAccount.getInstance().getCurrentUser());
                } else {
                    intent.putExtra(PUser.KEY, PAccount.getInstance().getCurrentUser());
                    intent.putExtra(PApp.KEY_NEXT, PUserActivity.class.getName());
                }
                break;
            case R.id.menu_about:
                intent.setClass(this, PAboutActivity.class);
                break;
            default:break;
        }
        startActivity(intent);

        return super.onOptionsItemSelected(item);
    }
}
